const express = require("express");
const router = express.Router();
const staffDao = require("../database/StaffDao");

// 获取所有员工
router.get("/list", async (req, res) => {
    try {
        const { department, entryTime, page = 1, pageSize = 10 } = req.query;
        const staffList = await staffDao.getAllStaff(department, entryTime);
        
        // 计算分页
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + parseInt(pageSize);
        const paginatedList = staffList.slice(startIndex, endIndex);
        
        res.send({
            code: 2000,
            msg: "获取员工列表成功",
            data: {
                list: paginatedList,
                total: staffList.length,
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                totalPages: Math.ceil(staffList.length / pageSize)
            }
        });
    } catch (error) {
        console.error('Error fetching staff list:', error);
        res.send({
            code: 5000,
            msg: "获取员工列表失败",
            data: null
        });
    }
});

// 获取所有职位
router.get("/positions/list", async (req, res) => {
    try {
        const positions = await staffDao.getAllPositions();
        res.send({
            code: 2000,
            msg: "获取职位列表成功",
            data: positions
        });
    } catch (error) {
        console.error('Error fetching positions:', error);
        res.send({
            code: 5000,
            msg: "获取职位列表失败",
            data: null
        });
    }
});

// 获取单个员工详情
router.get("/:id", async (req, res) => {
    try {
        const { id } = req.params;
        const staff = await staffDao.getStaffById(id);
        
        if (!staff) {
            return res.send({
                code: 4000,
                msg: "员工不存在",
                data: null
            });
        }
        
        res.send({
            code: 2000,
            msg: "获取员工信息成功",
            data: staff
        });
    } catch (error) {
        console.error('Error fetching staff:', error);
        res.send({
            code: 5000,
            msg: "获取员工信息失败",
            data: null
        });
    }
});

// 添加新员工
router.post("/", async (req, res) => {
    try {
        const { user_account, user_name, user_sex_id, user_position_id, user_entrytime } = req.body;
        
        // 验证必填字段
        if (!user_account || !user_name || !user_sex_id || !user_position_id || !user_entrytime) {
            return res.send({
                code: 4000,
                msg: "请填写所有必填字段",
                data: null
            });
        }
        
        // 检查账号是否已存在
        const accountExists = await staffDao.checkAccountExists(user_account);
        if (accountExists) {
            return res.send({
                code: 4000,
                msg: "员工账号已存在",
                data: null
            });
        }
        
        const newStaff = await staffDao.addStaff({ user_account, user_name, user_sex_id, user_position_id, user_entrytime });
        res.send({
            code: 2000,
            msg: "添加员工成功",
            data: newStaff
        });
    } catch (error) {
        console.error('Error adding staff:', error);
        res.send({
            code: 5000,
            msg: "添加员工失败",
            data: null
        });
    }
});

// 更新员工信息
router.put("/:id", async (req, res) => {
    try {
        const { id } = req.params;
        const { user_account, user_name, user_sex_id, user_position_id, user_entrytime } = req.body;
        
        // 验证必填字段
        if (!user_account || !user_name || !user_sex_id || !user_position_id || !user_entrytime) {
            return res.send({
                code: 4000,
                msg: "请填写所有必填字段",
                data: null
            });
        }
        
        // 检查员工是否存在
        const existingStaff = await staffDao.getStaffById(id);
        if (!existingStaff) {
            return res.send({
                code: 4000,
                msg: "员工不存在",
                data: null
            });
        }
        
        // 检查账号是否被其他员工使用
        const accountExists = await staffDao.checkAccountExists(user_account, id);
        if (accountExists) {
            return res.send({
                code: 4000,
                msg: "员工账号已被其他员工使用",
                data: null
            });
        }
        
        const updatedStaff = await staffDao.updateStaff(id, { user_account, user_name, user_sex_id, user_position_id, user_entrytime });
        res.send({
            code: 2000,
            msg: "更新员工信息成功",
            data: updatedStaff
        });
    } catch (error) {
        console.error('Error updating staff:', error);
        res.send({
            code: 5000,
            msg: "更新员工信息失败",
            data: null
        });
    }
});

// 删除员工
router.delete("/:id", async (req, res) => {
    try {
        const { id } = req.params;
        
        // 检查员工是否存在
        const existingStaff = await staffDao.getStaffById(id);
        if (!existingStaff) {
            return res.send({
                code: 4000,
                msg: "员工不存在",
                data: null
            });
        }
        
        await staffDao.deleteStaff(id);
        res.send({
            code: 2000,
            msg: "删除员工成功",
            data: null
        });
    } catch (error) {
        console.error('Error deleting staff:', error);
        res.send({
            code: 5000,
            msg: "删除员工失败",
            data: null
        });
    }
});

module.exports = router;